# -*- encoding: utf-8 -*-
import logging
import ast
import time
import copy
from datetime import datetime, timedelta
from django.conf import settings
from redis import StrictRedis
from offline_calc.handler import OfflineCalculationHandler
from common.dwc.qk.qk_handler import create_qk_user_info

_LOGGER = logging.getLogger(__name__)

redis = StrictRedis.from_url(settings.GENERAL_REDIS, charset="utf-8", decode_responses=True)


class Command(OfflineCalculationHandler):
    def __init__(self):
        super(Command, self).__init__()
        self.index_list = settings.DWC_INDEX

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)

    def timestamp_conversion(self, timestamp):
        time_array = time.localtime(timestamp)
        format_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
        return datetime.strptime(format_time, '%Y-%m-%d %H:%M:%S')

    # 以前註冊的用戶刷新一下數據
    def refresh_user_date(self):
        qk_users_info = ast.literal_eval(redis.get("qk_user_info")) if redis.get("qk_user_info") else {}
        copy_qk_users_info = copy.deepcopy(qk_users_info)
        for key, val in copy_qk_users_info.items():
            try:
                platform_id = val['platform_id']
                start_time = self.timestamp_conversion(val['start_time'])
                add_time = val['add_time']
                today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                if int(time.time()) - int(add_time) > 60:
                    create_qk_user_info(platform_id, user_pool=[key], start_time=start_time, end_time=today_start)
                    del (qk_users_info[key])
                    redis.set("qk_user_info", qk_users_info)
            except Exception:
                _LOGGER.exception('ES Create Report Error %s', key)

    def handle(self, **kwargs):
        super(Command, self).handle(**kwargs)
        for index in self.index_list:
            create_qk_user_info(index)
        self.refresh_user_date()
